package com.rodirod.vrmonitor;

import java.util.List;
import java.util.Map;

import com.rodirod.vrmonitor.R;

import android.app.ListActivity;
import android.app.NotificationManager;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;

/**
 * 
 * @author T0008086
 *
 */
public class RaceDetailedViewActivity extends ListActivity implements Constants {

	private static final String TAG = "RaceDetailedViewActivity";
	private String raceName_ = "RaceDetailedViewActivity";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.v(TAG, "OnCreate ");
		super.onCreate(savedInstanceState);

		raceName_ = this.getIntent().getStringExtra(M_EXTRA_REGATE_NAME);

		// Construct the adapter
		SimpleAdapter mList = new SimpleAdapter(this, 
				updateAdapterViewData(), 
				R.layout.regate_info_list_item, 
				new String[] {M_ICON, M_TITLE, M_VALUE},
				new int[] {R.id.info_view_row_icon, R.id.info_view_row_titre, R.id.info_view_row_value});
		setListAdapter(mList);

		// allow fast access with keyboard
		ListView lv = getListView();
		lv.setTextFilterEnabled(true);
		// add context menu on items
		registerForContextMenu(lv);
	}


	@Override
	protected void onResume() {
		Log.v(TAG, "onResume");
		super.onResume();
		// remove the notification ID (if any)
		int notificationID = this.getIntent().getIntExtra(M_EXTRA_NOTIFICATION_ID, -1);
		if (notificationID!=-1) {
			// Cancel the persistent notification.
			NotificationManager  mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			mNM.cancel(notificationID);
		}
		// notify a change to the dataset (prevent from any change done by the service)
		SimpleAdapter mList = (SimpleAdapter)getListAdapter();
		mList.notifyDataSetChanged();
	}



	@SuppressWarnings("unchecked")
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo adapterMenuInfo = (AdapterContextMenuInfo)item.getMenuInfo();
		View v = adapterMenuInfo.targetView;
		Map<String,Object> data = (Map<String,Object>)((ListView)v.getParent()).getItemAtPosition(adapterMenuInfo.position);

		boolean result = false;
		int monitorState = (Integer)data.get(M_MONITOR);

		switch (item.getItemId()) {
		case R.id.monitoredUp:
			if (!item.isChecked()) {
				item.setChecked(true);
				monitorState = I_MONITORED_UP;
			}
			result = true;
			break;
		case R.id.monitoredDown:
			if (!item.isChecked()) {
				item.setChecked(true);
				monitorState = I_MONITORED_DOWN;
			}
			result = true;
			break;
		case R.id.alarmed:
			if (!item.isChecked()) {
				item.setChecked(true);
				monitorState = I_MONITORED_ALARM;
			}
			result = true;
			break;
		case R.id.none:
			if (!item.isChecked()) {
				item.setChecked(true);
				monitorState = I_MONITORED_NONE;
			}
			result = true;
			break;
		default:
			result = super.onContextItemSelected(item);
			break;
		}

		setMonitorState(data,monitorState);

		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterContextMenuInfo adapterMenuInfo = (AdapterContextMenuInfo)menuInfo;
		Map<String,Object> data = (Map<String,Object>)((ListView)v).getItemAtPosition(adapterMenuInfo.position);
		Integer stateMonitor = (Integer) data.get(M_MONITOR);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.race_detail_context_menu, menu);

		MenuItem item = menu.getItem(stateMonitor.intValue());
		item.setChecked(true);
	}

	/**
	 * update the data for the listAdapter regarding the evolution of values.
	 * @return data for the listAdapter from the RegateInfo object
	 */
	private List<? extends Map<String, Object>> updateAdapterViewData() {
		RaceManager dataManager = RaceManager.getInstance();
		RaceInfo info = dataManager.getRace(raceName_);

		List<Map<String, Object>> result = info.getAdapterViewData();

		Map<String,Object> map;

		for (int i=0 ; i<result.size(); i++) {
			map = result.get(i);
			String currentValue = (String)map.get(M_VALUE);
			String refValue = (String)map.get(M_VALUE_REF);
			Object icon = map.get(M_ICON);

			Integer val = (Integer)map.get(M_MONITOR);
			switch (val.intValue()) {
			case I_MONITORED_NONE:
				icon = R.drawable.not_monitored;
				break;
			case I_MONITORED_UP:
				float currentVal = Float.parseFloat(currentValue);
				float refVal = Float.parseFloat(refValue);
				if (currentVal < refVal) {
					icon = R.drawable.down_arrow;
				} else if (currentVal > refVal) {
					icon = R.drawable.up_arrow;
				} else {
					icon = R.drawable.equal_arrow;
				}
				break;
			case I_MONITORED_DOWN:
				float currentVal2 = Float.parseFloat(currentValue);
				float refVal2 = Float.parseFloat(refValue);
				if (currentVal2 > refVal2) {
					icon = R.drawable.down_arrow;
				} else if (currentVal2 < refVal2) {
					icon = R.drawable.up_arrow;
				} else {
					icon = R.drawable.equal_arrow;
				}
				break;
			case I_MONITORED_ALARM:
				int alarmState = (Integer)map.get(M_ALARM_STATE);
				if (alarmState==I_ALARM_OFF) {
					icon = R.drawable.monitored;
				} else {
					icon = R.drawable.monitored_alm;
				}
				break;
			default:
				break;
			}
			map.put(M_ICON, icon);
		}
		return result;
	}

	private void setMonitorState(Map<String, Object> data, int monitorState) {
		data.put(M_MONITOR,monitorState);
		switch (monitorState) {
		case I_MONITORED_NONE:
			data.put(M_ICON, R.drawable.not_monitored);
			break;
		case I_MONITORED_UP:
			data.put(M_ICON, R.drawable.monitored);
			break;
		case I_MONITORED_DOWN:
			data.put(M_ICON, R.drawable.monitored);
			break;
		case I_MONITORED_ALARM:
			data.put(M_ICON, R.drawable.monitored);
			break;
		default:
			data.put(M_ICON, R.drawable.not_monitored);
			break;
		}
		SimpleAdapter mList = (SimpleAdapter)this.getListAdapter();
		mList.notifyDataSetChanged();
	}

//	// timer management
//	private Handler mHandler_ = new Handler();
//	private boolean timerStarted_ = false;
//	private int mTimerPeriodMs_ = 600000; //10 mn
//
//	public void startTimer() {
//		Log.v(TAG, "Timer started at " + DateUtils.formatDateTime(getBaseContext(),System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME));
//
//		if (timerStarted_) stopTimer();
//		mHandler_.removeCallbacks(mUpdateTimeTask_);
//		mHandler_.postDelayed(mUpdateTimeTask_, mTimerPeriodMs_);
//	}
//
//	public void stopTimer() {
//		Log.v(TAG, "Timer stopped at " + DateUtils.formatDateTime(getBaseContext(),System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME));
//		mHandler_.removeCallbacks(mUpdateTimeTask_);
//	}
//
//	Runnable mUpdateTimeTask_ = new Runnable() {
//		public void run() {
//			Log.v(TAG, "Timer called at " + DateUtils.formatDateTime(getBaseContext(),System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME));
//
//			RegateManager dataManager = RegateManager.getInstance();
//			RegateInfo info = dataManager.getRegate(regateName_);
//
//			info.readDataFromUrl();
//			updateAdapterViewData();
//
//			SimpleAdapter mList = (SimpleAdapter)getListAdapter();
//			mList.notifyDataSetChanged();
//
//			mHandler_.postDelayed(mUpdateTimeTask_, mTimerPeriodMs_);
//		}
//	};
}
